package com.stp.oversold.controller;

import com.stp.oversold.constant.R;
import com.stp.oversold.service.SecondKillService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * 使用数据自带的悲观锁
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class OversoldUpdateController {

    private final SecondKillService secondKillService;

    @PostMapping("/start/pes/lock/one")
    public R startPesLockOne(long skgId){
        try {
            log.info("开始秒杀方式三...");
            final long userId = (int) (new Random().nextDouble() * (99999 - 10000 + 1)) + 10000;
            R result = secondKillService.startSecondKillByUpdate(skgId, userId);
            if(result != null){
                log.info("用户:{}--{}", userId, result.getMsg());
            }else{
                log.info("用户:{}--{}", userId, "哎呦喂，人也太多了，请稍后！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }
}
